<?php

namespace App\Supports\Payment\Methods\Apple;

use Carbon\Carbon;
use App\Models\Order;
use App\Events\OrderPaidEvent;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;
use Brick\Math\RoundingMode;

class PayOrder extends Method implements MethodPay
{
	protected function isAppleEnough($order)
	{
		$useApples = big_decimal($order->total_amount)->dividedBy(cs("sale")->apple_actual_price,2,RoundingMode::HALF_UP);

		return $useApples->isLessThanOrEqualTo($order->user->apples);
	}

	public function validate($order = null)
	{
		if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
		if (!$this->isAppleEnough($order)) {
			fail('可用苹果不足');
		}
	}

	public function info($order = null) {}

	public function pay($order = null)
	{
		$this->validate($order);

		return DB::transaction(function () use ($order) {
			$order = Order::lockForUpdate()->find($order->id);
			$apples =(string)big_decimal($order->total_amount)->dividedBy(cs("sale")->apple_actual_price,2,RoundingMode::HALF_UP);
			$order->update(['paid_at' => Carbon::now(), 'paid_method' => 'apples','apples'=>$apples]);
			
            $data = ['order_id' => $order->id];
            account_apples($order->user)->minusAppleExchangeOrders($apples, $data);
			
			$order->unsetRelations();
			return $order;
		});
	}
}
